import axios, { AxiosRequestConfig } from "axios";
const qs = require('qs')
import { getToken,getTimeDate,toLogin,transformTime } from "@/utils";
import { Toast } from "vant";
// import { UserModule } from "@/store/modules/user";
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  // baseURL: "http://api.alldong.com/",
  headers: { "content-type": "application/x-www-form-urlencoded" }
});

interface DefaultParams {
  platform: string;
  token?: string;
}

// Request interceptors
service.interceptors.request.use(
  (config: any) => {
    const defaultParams: DefaultParams = {
      platform: "h5"
    };
  //刷新token
  // let date = transformTime(Number(getTimeout()) * 1000)
  // console.log(date,'date');
  if(getTimeDate() && getToken()) {
    let timeout = Number(getTimeDate())
    let date = (timeout - new Date().getTime() / 1000) 
    if(date <= 0) {
      toLogin()
    }
  }
    defaultParams.token = getToken();

    if (config.method === "get") {
      if (!config.params) {
        config.params = defaultParams;
      } else {
        config.params = Object.assign({}, config.params, defaultParams);
      }
    } else if (config.method === "post") {
      if (!config.data) {
        config.data = defaultParams;
      } else {
        config.data = Object.assign({}, config.data, defaultParams);
      }
      config.data = qs.stringify(config.data);
    }

    return config;
  },
  error => {
    Promise.reject(error);
  }
);
// Response interceptors
service.interceptors.response.use(
  response => {
    const res = response.data;
    if (res.code !== "200") {
      Toast(res.message)
      if (res.code === "301") {
        // UserModule.ResetToken();
        toLogin()
      }
      return Promise.reject(res.message);
    } else {
      return Promise.resolve(response.data.data);
    }
  },
  error => {
    return Promise.reject(error);
  }
);

export default function request(config: AxiosRequestConfig): any {
  return service(config);
}
